package com.example.jwtauthdemo.service.impl;


import com.example.jwtauthdemo.entity.CreateClass;
import com.example.jwtauthdemo.mapper.ClassMapper;
import java.util.List;

import com.example.jwtauthdemo.service.ClassService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ClassServceImpl implements ClassService {
    private static final Logger logger = LoggerFactory.getLogger(ClassServceImpl.class);

    @Autowired
    private ClassMapper classMapper;


    @Override
    public int insertClass(CreateClass createClass) {
        logger.info("开始插入班级数据: {}", createClass);
        int result = classMapper.insertClass(createClass);
        logger.info("插入完成，影响行数: {}", result);
        return result;
    }

    @Override
    public Integer selectClassCode(String classCode) {
        return classMapper.selectClassCode(classCode);
    }

    @Override
    public CreateClass selectClassInfo(String classCode) {
        return classMapper.selectClassInfo(classCode);
    }

    @Override
    public List<CreateClass> selectClassesByTeacherId(String teacherId) {
        return classMapper.selectClassesByTeacherId(teacherId);
    }
    
    @Override
    public List<CreateClass> selectClassesByUserIdAndRole(String userId, Integer role) {
        logger.info("查询用户ID: {}，角色: {} 关联的班级", userId, role);
        return classMapper.selectClassesByUserIdAndRole(userId, role);
    }

    @Override
    @Transactional
    public void dissolveClass(String teacherId, String classCode) {
        // 验证教师是否为班级所有者
        CreateClass classInfo = classMapper.selectClassInfo(classCode);
        if (classInfo == null || !classInfo.getTeacherId().equals(teacherId)) {
            throw new RuntimeException("无权解散该班级");
        }


        // 删除班级关联关系
        classMapper.deleteUserClassRelations(classCode);

        // 删除班级信息
        classMapper.deleteClassByCode(classCode);
    }


}